package com.atguigu.day03;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class Flink02_Transform_Map {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);

        //2.从端口读取数据
//        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);
        DataStreamSource<String> streamSource = env.readTextFile("input/sensor.txt");

        //TODO 3.使用Map将一行数据转为WaterSensor
//        SingleOutputStreamOperator<WaterSensor> map = streamSource.map(new MapFunction<String, WaterSensor>() {
//
//            @Override
//            public WaterSensor map(String value) throws Exception {
//                String[] words = value.split(" ");
//                return new WaterSensor(words[0], Long.parseLong(words[1]), Integer.parseInt(words[2]));
//            }
//        });
        SingleOutputStreamOperator<WaterSensor> map = streamSource.map(new MyRichMap());

        map.print();

        env.execute();
    }

    public static class MyRichMap extends RichMapFunction<String,WaterSensor>{

        /**
         * 生命周期方法 open 方法最先被调用 在每个并行度上调用一次
         * @param parameters
         * @throws Exception
         */
        @Override
        public void open(Configuration parameters) throws Exception {
            System.out.println("open...");
        }

        /**
         * 生命周期方法 close方法在程序最后被调用 在每个并行度上调用一次
         * 如果是从文件读数据，每个并行度close方法会调用两次
         * @throws Exception
         */
        @Override
        public void close() throws Exception {
            System.out.println("close...");
        }

        @Override
        public WaterSensor map(String value) throws Exception {
            System.out.println(getRuntimeContext().getTaskNameWithSubtasks());
            System.out.println(getRuntimeContext().getTaskName());
            String[] words = value.split(" ");
            return new WaterSensor(words[0], Long.parseLong(words[1]), Integer.parseInt(words[2]));
        }
    }
}
